package pers.jsan.litheopen.security.filter.client;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pers.jsan.litheopen.client.entity.LitheClient;
import pers.jsan.litheopen.client.service.ILitheClientService;
import pers.jsan.litheopen.security.exception.LitheAuthenticationException;
import pers.jsan.litheopen.security.filter.AuthenticationFilterChain;
import pers.jsan.litheopen.security.filter.LitheAuthenticationFilter;
import pers.jsan.litheopen.security.filter.RequestWrapper;
import pers.jsan.litheopen.security.oauth.model.ClientAccess;
import pers.jsan.litheopen.utils.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CheckClientAccessFilter implements LitheAuthenticationFilter {

    @Autowired
    private ILitheClientService litheClientService;

    @Override
    public void doFilter(HttpServletRequest servletRequest, HttpServletResponse servletResponse, AuthenticationFilterChain filterChain) throws IOException, ServletException, LitheAuthenticationException {
        RequestWrapper requestWrapper = new RequestWrapper(servletRequest);
        String body = requestWrapper.getBodyString();
        JSONObject jsonObject = JSONObject.parseObject(body);
        ClientAccess clientAccess = jsonObject.toJavaObject(ClientAccess.class);
        if(StringUtils.isEmpty(clientAccess.getClientId()) || StringUtils.isEmpty(clientAccess.getClientSecret())) {
            throw new LitheAuthenticationException("客户端授权码和秘钥异常");
        }
        LitheClient litheClient = litheClientService.getOne(new LambdaQueryWrapper<LitheClient>().eq(LitheClient::getClientId, clientAccess.getClientId()));
        if(null == litheClient || !MD5Util.encryption32(clientAccess.getClientSecret()).equals(litheClient.getClientSecret())) {
            throw new LitheAuthenticationException("客户端授权码和秘钥异常");
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
